// 权限拦截 路由守卫

import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const whitelist = ['/login', '/404'] // 白名单路由

router.beforeEach(async function(to, from, next) {
  NProgress.start()
  // 判断有无token
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      // 什么时候获取token
      if (!store.state.user.userInfo.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        const routes = await store.dispatch('permission/filterRoutes', roles.menus)
        router.addRoutes([...routes], { path: '*', redirect: '/404', hidden: true })
        next(to.path)
      }
      next()
    }
  } else {
    if (whitelist.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done()
})

router.afterEach(function() {
  NProgress.done()
})
